package com.cn.server.sever;

import com.cn.common.core.codc.ConstantValue;
import com.cn.common.core.codc.RequestDecoder;
import com.cn.common.core.codc.ResponseEncoder;
import com.cn.server.module.player.service.PlayerService;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.List;

/**
 * @Author: jia
 * @Descirption:
 * @Date: 2018/5/15 13:04
 * @Modified By:
 */

@ChannelHandler.Sharable
public class HandlerManager extends SimpleChannelInboundHandler<ByteBuf> {
    private EventLoopGroup serviceGroup;
    public HandlerManager(){}
    //构造方法
    public HandlerManager(EventLoopGroup serviceGroup) {
        this.serviceGroup = serviceGroup;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        Channel channel = ctx.channel();
        ChannelPipeline pipeline = channel.pipeline();
        System.out.println("当前线程====" + Thread.currentThread().getName());
        byte[] src = new byte[in.readableBytes()];
        ByteBuf copy = in.copy(0, in.readableBytes());
        boolean flag = false;
        while (copy.readableBytes() > 4) {
            copy.markReaderIndex();
            if (copy.readInt() == ConstantValue.HEADER_FLAG) {
                flag = true;
                break;
            }
            //恢复到标记位
            copy.resetReaderIndex();
            //略过一个字节
            copy.readByte();
        }
        //如果是pc自定义协议
        if (flag) {
            pipeline.addLast(new RequestDecoder());
            pipeline.addLast(new ResponseEncoder());
        //如果是websocket-》http协议
        } else {
            pipeline.addLast(new HttpServerCodec());
            //以块的方式来写的处理器
            pipeline.addLast(new ChunkedWriteHandler());
            //netty是基于分段请求的，HttpObjectAggreator的作用是将
            pipeline.addLast(new HttpObjectAggregator(8192));
            pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
            //帧的传输类型，这里使用的是处理文本类型的Handler
        }
        List<String> names = pipeline.names();
        //最后移除自己
        pipeline.remove(this.getClass());
        ctx.fireChannelRead(in);
    }
}
